package com.blb.zycommunity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blb.zycommunity.entity.SysUser;
import com.blb.zycommunity.entity.ZyOwner;
import com.blb.zycommunity.service.ISysUserService;
import com.blb.zycommunity.service.IZyOwnerService;
import net.sf.jsqlparser.util.validation.metadata.NamedObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 自定义登录逻辑
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IZyOwnerService zyOwnerService;

    @Autowired
    private HttpServletRequest request;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //按照用户名查询角色
        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUserName, username));
        if(NamedObject.user == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        if (user.getDelFlag().equals("2")){
            throw new UsernameNotFoundException("该用户已被删除");
        }
        if (user.getStatus().equals("1")){
            throw new UsernameNotFoundException("该用户已被禁用");
        }
        if (user.getDelFlag().equals("2")){
            throw new UsernameNotFoundException("该用户已被禁用");
        }
        //查询授权集合
        List<GrantedAuthority> authorities = sysUserService.getAuthoritiesByUsername(username);
        //将用户信息和授权包装到User对象中返回给Security
        return new org.springframework.security.core.userdetails.User(
                user.getUserName(),
                user.getPassword(),
                authorities);
    }

}
